<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-title">注册新账号</div>
      <div class="login-subtitle">欢迎注册RAG AI应用管理系统</div>
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="0">
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名" 
            size="large" 
            :prefix-icon="User" 
            clearable 
            @blur="validateField('username')"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱" 
            size="large" 
            :prefix-icon="Message" 
            clearable 
            @blur="validateField('email')"
          />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="请输入手机号" 
            size="large" 
            :prefix-icon="Phone" 
            clearable 
            @blur="validateField('phone')"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码" 
            size="large" 
            :prefix-icon="Lock" 
            show-password 
            clearable 
            @blur="validateField('password')"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            size="large" 
            :prefix-icon="Lock" 
            show-password 
            clearable 
            @blur="validateField('confirmPassword')"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            class="login-button" 
            type="primary" 
            :loading="loading" 
            :disabled="!isFormComplete()"
            @click="handleRegister"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        已有账号？<el-link type="primary" @click="goToLogin">返回登录</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone } from '@element-plus/icons-vue'
import { register } from '@/api/auth'

const router = useRouter()
const registerFormRef = ref()
const loading = ref(false)

const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
})

// 简化验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度3-20位', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (!value || value.trim().length === 0) {
          return new Error('用户名不能为空')
        }
        if (value.trim().length < 3) {
          return new Error('用户名至少3位')
        }
        if (value.trim().length > 20) {
          return new Error('用户名最多20位')
        }
        return true
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (!value || value.trim().length === 0) {
          return new Error('邮箱不能为空')
        }
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(value.trim())) {
          return new Error('邮箱格式不正确')
        }
        return true
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (!value || value.trim().length === 0) {
          return new Error('手机号不能为空')
        }
        if (!/^1[3-9]\d{9}$/.test(value.trim())) {
          return new Error('手机号格式不正确')
        }
        return true
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (!value || value.length === 0) {
          return new Error('密码不能为空')
        }
        if (value.length < 6) {
          return new Error('密码至少6位')
        }
        return true
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (!value || value.length === 0) {
          return new Error('请再次输入密码')
        }
        if (value !== registerForm.value.password) {
          return new Error('两次输入密码不一致')
        }
        return true
      },
      trigger: 'blur'
    }
  ]
}

// 实时验证字段
const validateField = (field) => {
  if (registerFormRef.value) {
    registerFormRef.value.validateField(field)
  }
}

// 检查表单是否完整
const isFormComplete = () => {
  const { username, email, phone, password, confirmPassword } = registerForm.value
  
  // 检查是否所有字段都有值
  if (!username || !email || !phone || !password || !confirmPassword) {
    return false
  }
  
  // 检查密码一致性
  if (password !== confirmPassword) {
    return false
  }
  
  return true
}

// 重新写的注册处理逻辑
const handleRegister = async () => {
  try {
    // 检查表单引用
    if (!registerFormRef.value) {
      ElMessage.error('表单初始化失败')
      return
    }

    // 先进行表单验证，只有全部通过才能继续
    try {
      await registerFormRef.value.validate()
    } catch (validationError) {
      console.log('表单验证失败:', validationError)
      ElMessage.warning('请完善表单信息，所有字段都必须填写正确')
      return
    }

    // 再次检查密码一致性（双重保险）
    if (registerForm.value.password !== registerForm.value.confirmPassword) {
      ElMessage.error('两次输入密码不一致')
      return
    }

    // 检查所有字段是否都有值
    const { username, email, phone, password, confirmPassword } = registerForm.value
    if (!username || !email || !phone || !password || !confirmPassword) {
      ElMessage.warning('请填写所有必填字段')
      return
    }

    // 设置加载状态
    loading.value = true

    // 准备注册数据
    const registerData = {
      Username: username.trim(),
      Password: password,
      Email: email.trim(),
      Phone: phone.trim()
    }

    console.log('发送注册请求，数据:', registerData)

    // 调用注册API
    const response = await register(registerData)
    console.log('注册API响应:', response)

    // 处理响应
    if (response && (response.code === 200 || response.Code === 200)) {
      ElMessage.success('注册成功！正在跳转到登录页面...')
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push({
          path: '/login',
          query: { username: username }
        })
      }, 1500)
    } else {
      // 处理业务逻辑错误
      const errorMsg = response?.message || response?.Message || '注册失败，请重试'
      ElMessage.error(errorMsg)
    }

  } catch (error) {
    console.error('注册异常:', error)
    
    // 处理不同类型的错误
    let errorMessage = '注册失败，请重试'
    
    if (error.response) {
      // HTTP错误响应
      const { status, data } = error.response
      console.log('HTTP错误状态:', status, '错误数据:', data)
      
      if (status === 400) {
        errorMessage = data?.message || data?.Message || '请求参数错误'
      } else if (status === 409) {
        errorMessage = data?.message || data?.Message || '用户名或邮箱已存在'
      } else if (status === 500) {
        errorMessage = '服务器内部错误，请稍后重试'
      } else {
        errorMessage = `请求失败 (${status})`
      }
    } else if (error.request) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置'
    } else if (error.message) {
      // 其他错误
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
    
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('@/assets/images/login-bg.svg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 20px;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}
.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(2px);
  z-index: 1;
  animation: backgroundPulse 8s ease-in-out infinite;
}
@keyframes backgroundPulse {
  0%, 100% { opacity: 0.1; }
  50% { opacity: 0.15; }
}
.login-card {
  position: relative;
  z-index: 2;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(16px) saturate(180%);
  -webkit-backdrop-filter: blur(16px) saturate(180%);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
  max-height: 90vh;
  overflow-y: auto;
}
.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-align: center;
  animation: titleGlow 4s ease-in-out infinite;
}
@keyframes titleGlow {
  0%, 100% { text-shadow: 0 0 8px rgba(102, 126, 234, 0.4); }
  50% { text-shadow: 0 0 25px rgba(102, 126, 234, 0.8); }
}
.login-subtitle {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0 0 30px 0;
  text-align: center;
}
.el-form {
  margin-bottom: 20px;
}
.el-form-item {
  margin-bottom: 20px !important;
}
.el-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}
.el-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: rgba(102, 126, 234, 0.3);
}
.el-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  border-color: #667eea;
}
.login-button {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}
.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}
.login-button:hover::before {
  left: 100%;
}
.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.3);
}
.login-button:active {
  transform: translateY(0);
}
.login-footer {
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
  margin-top: 18px;
}
.login-footer .el-link {
  font-size: 14px;
}
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
    margin: 10px;
  }
  .login-title {
    font-size: 24px;
  }
}
</style>